// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-6gz10xdd7d0548eb'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('云函数调用参数:', event)
  const { action, phone, password, nickname } = event
  switch (action) {
    case 'register':
      return await handleRegister(phone, password, nickname)
    case 'login':
      return await handleLogin(phone, password)
    case 'wxLogin':
      return await handleWxLogin()
    default:
      return {
        code: -1,
        msg: '未知的操作类型'
      }
  }
}

// 处理注册
async function handleRegister(phone, password, nickname) {
  try {
    // 检查手机号是否已注册
    const checkResult = await db.collection('users').where({
      phone: phone
    }).get()
    if (checkResult.data.length > 0) {
      return {
        code: -1,
        msg: '该手机号已注册'
      }
    }
    // 创建新用户
    const result = await db.collection('users').add({
      data: {
        phone,
        password,
        nickname: nickname || `用户${Date.now()}`,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })
    return {
      code: 0,
      msg: '注册成功',
      data: {
        _id: result._id
      }
    }
  } catch (error) {
    return {
      code: -1,
      msg: '注册失败',
      error: error
    }
  }
}

// 处理登录
async function handleLogin(phone, password) {
  try {
    const result = await db.collection('users').where({
      phone: phone,
      password: password
    }).get()
    if (result.data.length === 0) {
      return {
        code: -1,
        msg: '手机号或密码错误'
      }
    }
    const userInfo = result.data[0]
    delete userInfo.password // 不返回密码
    return {
      code: 0,
      msg: '登录成功',
      data: userInfo
    }
  } catch (error) {
    return {
      code: -1,
      msg: '登录失败',
      error: error
    }
  }
}

// 处理微信一键登录
async function handleWxLogin() {
  try {
    const wxContext = cloud.getWXContext()
    console.log('微信登录上下文:', wxContext)
    const openid = wxContext.OPENID
    if (!openid) {
      return {
        code: -1,
        msg: '获取openid失败'
      }
    }
    // 查询用户是否已存在
    let userRes = await db.collection('users').where({ openid }).get()
    let userInfo
    if (userRes.data.length === 0) {
      // 新用户自动注册
      const addRes = await db.collection('users').add({
        data: {
          openid,
          nickname: `微信用户${Date.now()}`,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
      userInfo = {
        _id: addRes._id,
        openid,
        nickname: `微信用户${Date.now()}`
      }
    } else {
      userInfo = userRes.data[0]
    }
    return {
      code: 0,
      msg: '登录成功',
      data: userInfo
    }
  } catch (error) {
    console.error('微信登录错误:', error)
    return {
      code: -1,
      msg: '微信登录失败',
      error: error
    }
  }
}